#!/usr/bin/perl
#

open(MOR,$ARGV[0]);
while($morLine=<MOR>) {
	chomp($morLine);
	($num,$word,$morph) = split(/\t+/,$morLine);
	@morphEntries = split(/[\|]/,$morph);
	$entryNum=0;
	foreach $entry (@morphEntries) {
		$entry=~/<fs af='([^']+)'>/;
		@fields=split(/,/,$1);
		$myMorph{$word}->[$entryNum]->{'root'} = $fields[0];
		$myMorph{$word}->[$entryNum]->{'cat'} = $fields[1];
		$myMorph{$word}->[$entryNum]->{'gen'} = $fields[2];
		$myMorph{$word}->[$entryNum]->{'num'} = $fields[3];
		$myMorph{$word}->[$entryNum]->{'per'} = $fields[4];
		$myMorph{$word}->[$entryNum]->{'obl'} = $fields[5];
		$myMorph{$word}->[$entryNum]->{'tam'} = $fields[7];
		$entryNum++;
	}
}
close(MOR);

open(COMPAT,$ARGV[1]);
while($compat=<COMPAT>) {
	chomp($compat);
	($oldPos,$newPos) = split(/\s+/,$compat);
	$compat{"$oldPos $newPos"} = 1;
}
close(COMPAT);


while($line=<STDIN>) {
	chomp($line);
	if($line=~/^#([0-9]+)\s+(.*)$/) {
		$word = $2;
		print $line."\n";

		$line=<STDIN>;
		chomp($line);
		$line=~/pos:\s*(.*)$/;
		$pos = $1;
		print $line."\n";
		
		my $correctEntry = "";
		for($j=0;$j<(@{$myMorph{$word}});$j++) {
			$entry = $myMorph{$word}->[$j];
			if($compat{"$pos $entry->{'cat'}"}) {
				$correctEntry = $entry;
				last;
			}
		}

		if($myMorph{$word}) {
			if(!$correctEntry) {
				$correctEntry = $myMorph{$word}->[0];
			}

			print "\troot: $correctEntry->{'root'}\n";
			print "\tgnp: ".$correctEntry->{'gen'}.$correctEntry->{'num'}.$correctEntry->{'per'}."\n";
		}
		else {
			print "\troot: $word\n";
			print "\tgnp: x3sg\n";
		}

	}
	else {
		print $line."\n";
	}
}


